package javaMultiThreadInAction.chapter02;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 2-1 RequestId生成器
 * @date 2024/1/10 09:29:37
 */
public class RequestIDGenerator implements CircularSeqGenerator {
    private final static RequestIDGenerator INSTANCE = new RequestIDGenerator();
    private final static short SEQ_UPPER_LIMIT = 999;
    private volatile short sequence = -1;

    private RequestIDGenerator() {

    }

    /**
     * 生成循环递增序号
     *
     * @return
     */
    @Override
    public short nextSequence() {
        if (sequence > SEQ_UPPER_LIMIT) {
            sequence = 0;
        } else {
            sequence++;
        }
        return sequence;
    }

    public short syncNextSequence() {
        synchronized (this) {
            if (sequence > SEQ_UPPER_LIMIT) {
                sequence = 0;
            } else {
                sequence++;
            }
            return sequence;
        }
    }

    public String nextID() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String timestamp = sdf.format(new Date());
        DecimalFormat df = new DecimalFormat("000");

//        short sequenceNo = nextSequence();
        short sequenceNo = syncNextSequence();
        return "0049" + timestamp + df.format(sequenceNo);
    }

    public static RequestIDGenerator getInstance() {
        return INSTANCE;
    }

}
